﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Test.Expressions;
using System.Linq.Expressions;

namespace Test.ExpressionVisitors
{

	internal class SubqueryExpressionFinder : ExpressionVisitor
	{
		internal SubqueryExpression found;
		/// <summary>
		/// Finds and returns the first SubqueryExpression it encounters.
		/// </summary>
		/// <param name="expression"></param>
		/// <returns></returns>
		public static SubqueryExpression Find(Expression expression) {
			var finder = new SubqueryExpressionFinder();			
			finder.Visit(expression);
			return finder.found;
		}
		public override Expression Visit(Expression node) {
			switch ((DbExpressionType)node.NodeType) {
				case DbExpressionType.Select:
				case DbExpressionType.Subquery:
				case DbExpressionType.Min:
				case DbExpressionType.Max:
				case DbExpressionType.Sum:
				case DbExpressionType.Average:
				case DbExpressionType.Count:
					this.found = (SubqueryExpression)node;
					return this.found;				
				case DbExpressionType.Join:										
					this.found = this.Visit(((JoinExpression)node).Second) as SubqueryExpression;										
					return this.found;
				case DbExpressionType.CrossApply:					
					this.found = this.Visit(((CrossApplyExpression)node).Second) as SubqueryExpression;										
					return this.found;
			}

			return node;
		}
	}
}
